/* Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

 * Author:  Lance Sims
 * Date:    12.26.2008
 * version  1.0
 * Modified by Mike Slinn */
 
package view.components {
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard;
    import view.components.ResizableTitleWindow;
    import mx.containers.TitleWindow;
    import mx.effects.Effect;
    import mx.effects.Iris;
    import mx.effects.Move;
    import mx.effects.Resize;
    import mx.events.CloseEvent;
    import mx.events.EffectEvent;
    import mx.events.FlexEvent;
    import mx.managers.PopUpManager;


    /** This class allows users to specify animations for opening a pop up/title window as well as when it is closed */
    public class AnimatedTitleWindow extends ResizableTitleWindow {
        /** @private the start effect */
        private var openEffect:Effect;
        
        /** @private the end effect */
        private var closeEffect:Effect;
        
        /** @private the open duration */
        private var defaultOpenDuration:int;
        /** @private the close duration */
        private var defaultCloseDuration:int;
        
        /** @private nWidth */
        private var w:Number;
        
        /** @private the height */
        private var h:Number;


        /** @param effect the effect that the pop up will use to animate the opening of the title window
         * @param closeEffect the effect that the pop up will use when closing
         * @param openDuration the duration for the opening effect if it has not been set on the openEffect
         * @param closeDuration the duration of the close effect if it has not been set;
         * both parameters are defaulted to null and if either is null the default behavior will animate the title window on open and close
         * when the component animates itself closing it will reverse the close effect so if you use a wipe effect it will
         * do the exact opposite, e.g. a WipeUpInstance will behave like a WipeDown */
        public function AnimatedTitleWindow(openEffect:Effect=null, closeEffect:Effect=null, defaultOpenDuration:int=500, defaultCloseDuration:int=500) {
            super();
            try {
                this.defaultOpenDuration = defaultOpenDuration;
                this.defaultCloseDuration = defaultCloseDuration;
                this.openEffect = (openEffect == null) ? openEffectDefault() : openEffect;
                this.closeEffect = (closeEffect == null) ? closeEffectDefault() : closeEffect;
                this.openEffect.play([this]);
                horizontalScrollPolicy = "auto";
                verticalScrollPolicy = "auto";
                addEventListener(FlexEvent.CREATION_COMPLETE, onCreationComplete);
                addEventListener(CloseEvent.CLOSE, onClose);
            } catch (error:Error) {
                throw new Error("Error in constructor " + error.message);
            }
        }

        private function checkKey(event:KeyboardEvent):void {
            if (event.keyCode==Keyboard.ESCAPE) {
                event.stopPropagation();
                event.stopImmediatePropagation();
                onClose(null);
            }
        }
        
        public function onCancel(event:FlexEvent):void { onClose(null); }
        
        /** @protected the close handler for the close event
         * @param event an instance of a close event */
        public function onClose(event:CloseEvent):void {
            try {
                if (event)
                    event.stopImmediatePropagation();
                //determine if we should play the reverse of the animation (resize, wipes, move?)
                var playReverse:Boolean = true;
                if (closeEffect is Resize || closeEffect is Move) 
                    playReverse = false;
                setWidthHeight();
                //play the close effect and add an event listener for the effect end
                //if the effect is not a resize effect then play the close effect in reverse
                closeEffect.play([this], playReverse);
                closeEffect.addEventListener(EffectEvent.EFFECT_END, onCloseEffectEnd);
            } catch (error:Error) {
                throw new Error("Error in onClose() " + error.message);
            }
        }

        /** @private the event handler for when the close effect has finished playing
         * @param event an instance of an effectEvent
         * re-dispatch the close event once the effect has completed playing so that the developer using this component can handle
         * the close event the way they choose */
        private function onCloseEffectEnd(event:EffectEvent):void {
            try {
                // Remove the event listener for the close event so that this component doesn't 
                // replay the animation and stop the close event
                removeEventListener(CloseEvent.CLOSE, onClose);
                dispatchEvent(new CloseEvent(CloseEvent.CLOSE));
                PopUpManager.removePopUp(this);
            } catch (error:Error) {
                throw new Error("Error in onCloseEffectEnd " + error.message);
            }
        }

        private function onCreationComplete(event:FlexEvent):void {
            PopUpManager.centerPopUp(this);
            setFocus();
            stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKey);
        }

        /** @private set the default close effect if the close effect is null */
        private function closeEffectDefault():Effect {
            horizontalScrollPolicy = "off";
            verticalScrollPolicy = "off";
            var rsz:Resize = new Resize();
            rsz.duration = defaultCloseDuration;
            // ccallendar, June 21st - setting the width and height to 0 causes exceptions
            // the Tree and List controls throw an exception when drawing the selection indicator
            // and the width/height is 0
            rsz.heightTo = 10;
            rsz.widthTo = 10;
            rsz.suspendBackgroundProcessing = true;
            return rsz;
        }

        /**  @private set the default open effect if the open effect is null */
        private function openEffectDefault():Effect {
            var iris:Iris = new Iris();
            iris.duration = defaultOpenDuration;
            iris.suspendBackgroundProcessing = true;
            return iris;
        }

        /** @private if the AnimatedTitleWindow width or height is 0 we set it here so that the close effect can play properly
         * loop over children and get the greatest height and width from them and set the window width according to those */
        private function setWidthHeight():void {
            try {
                if (width == 0 || height == 0) {
                    for (var i:int = 0; i < this.getChildren().length; i++) {
                        getChildAt(i).width > w ? w = getChildAt(i).width : w = w;
                        getChildAt(i).height > h ? h = getChildAt(i).height : h = h;
                    }
                    //just in case there is a 0 give the component a default height and width
                    w == 0 ? w = 300 : w = w;
                    h == 0 ? h = 300 : h = h;
                    //now set the width and height of this component
                    width = w;
                    height = h;
                }
            } catch (error:Error) {
                throw new Error("Error in setWidthHeight " + error.message);
            }
        }
    }
}